import React, { useContext, useEffect, useState, useCallback } from 'react'
import {useHistory} from 'react-router-dom'
import { postAccOverallISendOutApprove, getAccOverallRevocation } from '../../financialApi'
import FoundFrom from './components/FoundFrom'
import SelectModule from './components/SelectModule'
import {
    myContext
} from '../../../../reducer'
import {
    MyApprovalType
} from '../../../../assets/enum'
import { MyApprovalAll } from './style'
import { message, PageHeader, Button, Space, Table, Spin, Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { confirm } = Modal;

/**
 * @description: 财务-我的审核-页面
 * @author: xiaoxujs
 * @upDate: xiaoxujs（2021-07-07）
 */

const MyApproval = () => {
    const history = useHistory()
    const { state } = useContext(myContext);
    const [listData, setListData] = useState([])
    const [foundFromVisible, setFoundFromVisible] = useState(false)
    const [spinning, setSpinning] = useState(false)
    const [total, setTotal] = useState(0)
    const [currentPage, setCurrentPage] = useState(1)
    const [size, setSize] = useState(10)
    const [selectData, setSelectData] = useState({})

    const listFun = useCallback(
        (parames = {
            currentPage: 1,
            size: 10
        }) => {
            parames.examineStatus = state.myApprovalType
                ; (async () => {
                    setSpinning(true)
                    const { code, msg, data } = await postAccOverallISendOutApprove(parames)
                    if (code === '20000') {
                        setSpinning(false)
                        setListData(data.records)
                        setTotal(data.total)
                        setCurrentPage(parames.currentPage)
                        setSize(parames.size)
                    } else {
                        message.error(msg)
                    }
                })()
        },
        [state.myApprovalType],
    )
    useEffect(() => {
        listFun()
    }, [listFun])
    // const handleFoundForm = () => {
    //     setFoundFromVisible(true)
    // }
    const handleSelect = (values) => {
        values.examineStatus = state.myApprovalType
        values.currentPage = 1
        values.size = 10
        setSelectData(values)
        listFun(values)
    }
    //分页
    const pagination = {
        //是否可以改变pagesize//
        showSizeChanger: true,
        //是否可以快速跳转到某页
        showQuickJumper: true,
        //展示一共有多少条数据//
        showTotal: () => `共${total}条`,
        //每页条数
        pageSize: size,
        //当前页数
        current: currentPage,
        //数据总数
        total: total,
        //pageSize 变化的回调
        onShowSizeChange: (current, pageSize) => changePageSize(pageSize, current),
        //页码改变的回调，参数是改变后的页码及每页条数
        onChange: (current) => changePage(current),
    }
    //改变每页条数
    const changePageSize = (pageSizeFun, current) => {
        const page = {
            currentPage: current,
            size: pageSizeFun
        }
        const parames = Object.assign(selectData, page)
        listFun(parames);
    }
    //改变页数
    const changePage = (current) => {
        const page = {
            currentPage: current,
            size
        }
        const parames = Object.assign(selectData, page)
        listFun(parames);
    }
    //撤销
    const handleCancel = (serialNo) => {
        confirm({
            title: '确定要撤消申请吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                ;(async () => {
                    const {code, msg} = await getAccOverallRevocation({serialNo})
                    if(code === '20000') {
                        const page = {
                            currentPage,
                            size
                        }
                        const parames = Object.assign(selectData, page)
                        listFun(parames);
                        message.success('撤销成功!')
                    }else{
                        message.error(msg)
                    }
                })()
            }
          });
    }
    //进入详情
    const handleEnterDetails = (sub, serialNo) => {
        history.push({pathname: '/myApproval/details', state: {sub, serialNo}})
    }
    //重新提交
    const handleAgainSubmit = (sub, serialNo) => {
        history.push({
            pathname: '/financialApplyForm', state: {
                serialNo,
                financialApplyType: sub
            }
        })
    }
    const columns = [
        {
            title: '流水号',
            dataIndex: 'serialNo',
            render: (text, recode) => <Button 
                type = 'link' 
                style = {{padding: '0px'}} 
                onClick = {() => handleEnterDetails(recode.sub, recode.serialNo)}
            >
                {text}
            </Button>
        },
        {
            title: '申请人',
            dataIndex: 'applicant'
        },
        {
            title: '经办人',
            dataIndex: 'agentName'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime'
        },
        {
            title: '申请金额（元）',
            dataIndex: 'money'
        },
        {
            title: '申请事由',
            dataIndex: 'matter'
        },
        {
            title: '当前审批阶段',
            dataIndex: 'taskName'
        },
        {
            title: '审批事项',
            render: (text, recode) => <span>{recode.model.describe}</span>
        },
        {
            title: '操作',
            render: (text, record) => (
                <Space size="middle">
                    {
                        state.myApprovalType === 0 ? <Button type = 'primary' onClick = {() => handleCancel(record.serialNo)} >撤销</Button> : null
                    }
                    {
                        state.myApprovalType === 2 ? <Button type = 'primary' onClick = {() => handleAgainSubmit(record.sub, record.serialNo)} >重新审批</Button> : null
                    }
                </Space>
            ),
        },
    ];
    return <MyApprovalAll>
        <PageHeader
            className="site-page-header"
            title={MyApprovalType[state.myApprovalType]}
            // extra={[
            //     <Button key='1' type='primary' onClick={() => handleFoundForm()}>创建申请单</Button>
            // ]}
        />
        <SelectModule listFun={listFun} handleSelect={handleSelect} setSelectData = {setSelectData} />
        <Spin tip="加载中..." spinning={spinning}>
            <Table columns={columns} dataSource={listData} rowKey='id' pagination = {pagination} />
        </Spin>

        <FoundFrom
            foundFromVisible={foundFromVisible}
            setFoundFromVisible={setFoundFromVisible}

        />
    </MyApprovalAll>
}

export default MyApproval;